package com.thread.threadfirst.studyThread3;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 4、写时复制copy on write
 * 多线程环境下，写效率低，读效率高
 * 适合写少读多的环境，比如 事件监听器队列就适用于读多写少的情况（读不加锁、写加锁）
 */
public class T2 {
    public static void main(String[] args) {
        List<String> list =
//                new ArrayList();    //有并发问题
//                new Vector<>();
                new CopyOnWriteArrayList<>();   //copy-on-write 适用于读多写少的情况下(且读的时候不需要加锁)，所以此处不适用。需要4500毫秒

        Thread[] thr = new Thread[100];
        Random ran = new Random();

        for (int i = 0; i < thr.length; i++) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000; j++) list.add("a" + ran.nextInt(10000));
                }
            };
            thr[i] = new Thread(r);
        }
        runAndComputeTime(thr);
        System.out.println(list.size());

    }

    public static void runAndComputeTime(Thread[] threads) {
        long start = System.currentTimeMillis();
        Arrays.asList(threads).forEach(o -> o.start());
        Arrays.asList(threads).forEach(o -> {
            try {
                o.join();  //先让所有子线程执行完，再让主线程往下执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }

}
